export default class InvokeUtil {
  static once(bound, p) {
    let firstInvoke = false
    if (!bound.__invoking) {
      bound.__invoking = true
      firstInvoke = true
    } else {
      bound.__invokingQuee = bound.__invokingQuee || []
    }
    return new Promise((resolve, reject) => {
      if (firstInvoke) {
        p().then(data => {
          resolve(data)
          if (bound.__invokingQuee) {
            bound.__invokingQuee.forEach(i => {
              i.resolve(data)
            })
          }
        }).catch(e => {
          reject(e)
          if (bound.__invokingQuee) {
            bound.__invokingQuee.forEach(i => {
              i.reject(e)
            })
          }
        }).finally(() => {
          bound.__invoking = false
          delete bound.__invokingQuee
        })
      } else {
        bound.__invokingQuee.push({
          reject,
          resolve
        })
      }
    })
  }
}
